iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 26
0
Mobile Development

iOS Developer Learning Android系列 第 26

iOS Developer Learning Android. Lesson 26 - FCM Notification (Service & BroadcastReceiver)

  • 分享至 

  • xImage
  •  

本日效果

實作

  1. Firebase已經被整合進AS了
  2. 選Cloud Messaging來實作推播
  3. 幫你在Firebase建立專案並整進AS
  4. 安裝library
  5. File > New > Service > Service > 繼承FirebaseMessagingService
public class IDLAFirebaseMessagingService extends FirebaseMessagingService
{
    public IDLAFirebaseMessagingService() { }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage)
    {
        // TODO(developer): Handle FCM messages here.
        // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d("MF❤️", "From: " + remoteMessage.getFrom());
    }
}
  1. 去console.firebase.google.com發推播
  2. 其實這時已經可以收到推播了⚠️⚠️⚠️不像iOS還要取得權限
  3. 實作前景也能顯示在system tray
    (如果APP在背景時,不會call onMessageReceived,但Android會幫你顯示到system tray)
            RemoteMessage.Notification remoteNotif = remoteMessage.getNotification();

            Notification notif = new NotificationCompat.Builder(this,"NotificationChannelID")
                    .setSmallIcon(R.drawable.chess_knight)
                    .setContentTitle(remoteNotif.getTitle())
                    .setContentText(remoteNotif.getBody())
                    .build();

            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.notify(999,notif);
  1. 透過LocalBroadcastManager跟BroadcastReceiver來廣播給Activity⚠️⚠️⚠️不像iOS一個NotificationCenter搞定
//onMessageReceived時發出廣播
        Intent intent = new Intent("FCM");
        intent.putExtra("notifi",message);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
//Activity
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lesson21);

        textView = findViewById(R.id.textView15);

        broadcastReceiver = new BroadcastReceiver()
        {
            @Override
            public void onReceive(Context context, Intent intent)
            {
                textView.setText(intent.getStringExtra("notifi"));
            }
        };
    }

    @Override
    protected void onStart()
    {
        super.onStart();
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter("FCM"));
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
    }

補充說明

  • ⚠️⚠️⚠️不像iOS一定要走APNs,他們也可以不透過FCM,像在中國Google不通,就要用其他的推播服務
  • Service跟Activity一樣,新增的時候會自動幫你加入到AndroidManifest
  • 如果之前能收到推播,然後突然收不到了,請檢查AS右下角的Event Log,裡面有紅字的DNS錯誤的話就重開一下
  • 模擬器是可以收到推播的(跟iOS相比他們的模擬器簡直是萬能的⚠️⚠️⚠️)
  • Display Messages: These messages trigger the onMessageReceived() callback only when your app is in foreground
    Data Messages: Theses messages trigger the onMessageReceived() callback even if your app is in foreground/background/killed

  • 拿到推播token的方法
        FirebaseInstanceId
            .getInstance()
            .getInstanceId().addOnCompleteListener(new OnCompleteListener<InstanceIdResult>()
        {
            @Override
            public void onComplete(@NonNull Task<InstanceIdResult> task)
            {
                if (task.isSuccessful() && task.getResult() != null)
                {
                    Log.d("MF❤️", "FCM token: " + task.getResult().getToken());
                }
            }
        });

參考資料

今天的範例程式

可以去 https://github.com/mark33699/IDLA 看一下順便給顆⭐️


如果你喜歡我的影片別忘了按讚分享加訂閱,開啟紅色的小鈴鐺,我們明天見~


上一篇
iOS Developer Learning Android. Lesson 25 - ActionBar (就算沒有NavigationController還是要處理那條bar喔)
下一篇
iOS Developer Learning Android. Lesson 27 - APP Widget (讓user不用開你的APP就能用你的APP)
系列文
iOS Developer Learning Android30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言